import json
import datetime
from django.db import transaction
from django.db.models import Q

from project.models import TbFenbi, Kg, WordKnowledgepoints, KgCopy, TbFenbiNorepeat
from .Tools import queryset_to_list
from .dataProcessor.KgDataProcessor import KgDataProcessor
from question.models import KgManualSourceNorepeat, TbFenbiV2Norepeat


def test():
    # make_knowledge_point_name()
    # KgDataProcessor().run()
    # make_fenbiv2_norepeat
    rx_question_kg()


def make_fenbiv2_norepeat():
    questions = TbFenbiV2Norepeat.objects.filter(uid__gte=8061)
    questions_count = questions.count()
    for i in range(questions_count):
        question = questions[i]
        # chapter = WordKnowledgepoints.objects.filter(point_name=question.chapter_name)[0]
        question.choice = {
            "a": question.choice_a,
            "b": question.choice_b,
            "c": question.choice_c,
            "d": question.choice_d,
        }
        question.single_or_multiple = 1
        # question.chapter_id = chapter.point_id
        question.answer = [question.answer]
        question.subject = "行测"
        question.insert_to_kg = 1
        question.save()
"""
去重后的tb_fenbi_copy 入库kg 
先根据kg记录去重tb_fenbi_copy 
再插入kg表
"""


def rx_question_kg():
    kg_query = Kg.objects.all().values()
    kg_query_count = kg_query.count()
    for i in range(kg_query_count):
        kg_question = kg_query[i]
        fenbi_query = TbFenbiV2Norepeat.objects.filter(stem=kg_question["stem"])
        fenbi_query_count = fenbi_query.count()
        fenbi_query.delete()
        if(fenbi_query_count>0):
            print("fenbi_query_count" + str(i), fenbi_query_count)


"""
去重后的tb_fenbi_copy 入库kg 
先根据kg记录去重tb_fenbi_copy 
再插入kg表
"""


def tbFenbiV2_to_kg():
    kg_query = Kg.objects.all().values()
    kg_query_count = kg_query.count()
    for i in range(kg_query_count):
        kg_question = kg_query[i]
        fenbi_query = TbFenbiV2Norepeat.objects.filter(stem=kg_question["stem"])
        fenbi_query_count = fenbi_query.count()
        fenbi_query.delete()
        print("fenbi_query_count" + str(i), fenbi_query_count)


"""
去重后的tb_fenbi_copy 入库kg 
先根据kg记录去重tb_fenbi_copy 
再插入kg表
"""


def tb_fenbi_copy_to_kg():
    kg_query = Kg.objects.all().values()
    kg_query_count = kg_query.count()
    for i in range(kg_query_count):
        kg_question = kg_query[i]
        fenbi_query = TbFenbiNorepeat.objects.filter(content=kg_question["stem"])
        fenbi_query_count = fenbi_query.count()
        fenbi_query.delete()
        print("fenbi_query_count" + str(i), fenbi_query_count)


"""
去重后的tb_fenbi_copy 入库kg 
先根据kg记录去重tb_fenbi_copy 
再插入kg表
"""


def kg_manual_source_norepeat_to_kg():
    kg_query = Kg.objects.all().values()
    kg_query_count = kg_query.count()
    for i in range(kg_query_count):
        kg_question = kg_query[i]
        fenbi_query = KgManualSourceNorepeat.objects.filter(stem=kg_question["stem"])
        fenbi_query_count = fenbi_query.count()
        fenbi_query.delete()
        print("fenbi_query_count" + str(i), fenbi_query_count)


def kg_manual_source_norepeat_choice():
    questions = KgManualSourceNorepeat.objects.all()
    questions_count = questions.count()
    for i in range(questions_count):
        question = questions[i]
        choice = eval(question.choices)
        chapter = WordKnowledgepoints.objects.get(point_name=question.chapter)
        question.choice_a = choice.get("a")
        question.choice_b = choice.get("b")
        question.choice_c = choice.get("c")
        question.choice_d = choice.get("d")
        question.question_source = 'gc'
        question.chapter_id = chapter.point_id
        question.exam_type = "行测"
        question.create_time = str(datetime.datetime.now())
        question.save()


"""
将tb_fenbi 入库kg
"""


def insert_into_kg():
    questions = TbFenbi.objects.filter(~Q(insert_to_kg=1))
    questions_count = questions.count()
    print(questions_count)
    for i in range(questions_count):
        question = questions[i]
        question_info = json.loads(question.question)
        # 获取选项
        # --- start ---
        accessories = question_info.get("accessories")
        exam_type = question.exam_type
        print(accessories)
        if (len(accessories) > 0):
            choice_list = accessories[0].get("options")
        else:
            choice_list = ["", "", "", ""]
        # --- end ---
        correctAnswer = question_info.get("correctAnswer")
        answer = correctAnswer.get("choice")
        answer = check_choice_num(answer)
        # chapter
        chapter = question.project
        chapter_obj = WordKnowledgepoints.objects.filter(point_name=chapter)[0]
        chapter_id = chapter_obj.point_id
        kg_info = {
            "stem": question.content,
            "single_or_multiple": 1,
            "choices": {
                "a": choice_list[0],
                "b": choice_list[1],
                "c": choice_list[2],
                "d": choice_list[3]
            },
            "choice_a": choice_list[0],
            "choice_b": choice_list[1],
            "choice_c": choice_list[2],
            "choice_d": choice_list[3],
            "is_marked": 0,
            "answer": answer,
            "explanation": question_info.get("solution"),
            "source": question_info.get("source"),
            "chapter": question.project,
            "subject": "公务员行测",
            "subject_id": 1,
            "chapter_id": chapter_id,
            "is_delete": 0,
            "material": question_info.get("material"),
            "question_id": question_info.get("question_id"),
            "exam_type": exam_type
        }
        kg_info = add_datetime(kg_info)
        with transaction.atomic():
            KgCopy.objects.create(**kg_info)
            question.insert_to_kg = 1
            question.save()


"""
填写kg表中的材料
"""


def get_meterial():
    stem = "<p>2020年，我国软件和信息技术服务业营业利润率（利润总额/业务收入）比上年：</p>"
    fenbi = TbFenbi.objects.filter(content=stem)


"""
修正kg表中的答案
"""


def amend_kg_answer():
    questions = Kg.objects.filter(create_time__gte="2023-6-20")
    question_count = questions.count()
    for i in range(question_count):
        question = questions[i]
        stem = question.stem
        source_question = TbFenbi.objects.filter(content=stem)
        current_answer = source_question[0].correct_answer
        print("current_answer", json.loads(current_answer).get("choice"))
        answer = check_choice_num(json.loads(current_answer).get("choice"))
        print("answer", answer)
        question.answer = answer
        print("create_time", question.create_time)
        question.save()
        print("-------------")


#  --- tools ---
def amend_answer(answer):
    print("type", type(answer))
    match answer:
        case "['']":
            return ["a"]
        case "['a']":
            return ["b"]
        case "['b']":
            return ["c"]
        case "['c']":
            return ["d"]
        case _:
            return [""]


def check_choice_num(choice_num):
    match choice_num:
        case "0":
            return ["a"]
        case "1":
            return ["b"]
        case "2":
            return ["c"]
        case "3":
            return ["d"]
        case _:
            return [""]


def add_datetime(info):
    now = str(datetime.datetime.now())
    info["create_time"] = now
    info["update_time"] = now
    return info


def make_knowledge_point_name():
    w_query = WordKnowledgepoints.objects.all()
    count = w_query.count()
    for i in range(count):
        update_info = {
            "id": w_query[i].id,
            "point_name": w_query[i].point_name.rstrip('\n')
        }
        w_query[i].point_name = update_info["point_name"]
        w_query[i].save()
        print(w_query[i].point_name)
        # w_query[i].save()
